package com.derbysoft.lowcostadapter.dswitch3.handler.impl;

import com.derbysoft.dswitch.dto.common.KeyValue;
import com.derbysoft.dswitch.remote.hotel.dto.HotelReservationRequest;
import com.derbysoft.dswitch.remote.hotel.dto.HotelReservationResponse;
import com.derbysoft.lowcostadapter.commons.log.TransactionLogger;
import com.derbysoft.lowcostadapter.commons.model.OperationType;
import com.derbysoft.lowcostadapter.commons.model.ReservationLog;
import com.derbysoft.lowcostadapter.dswitch2.service.helper.Constant;
import com.derbysoft.lowcostadapter.dswitch3.handler.RemoteServiceHandler;
import com.derbysoft.lowcostadapter.dswitch3.service.HotelProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * Created by: jason
 * Date: 2012-05-22
 */
@Component("hotelReservationHandler")
public class HotelReservationHandler extends AbstractDSwitch3Handler<HotelReservationRequest, HotelReservationResponse>
        implements RemoteServiceHandler<HotelReservationRequest, HotelReservationResponse> {

    @Autowired
    @Qualifier("ds3HotelReservationService")
    protected HotelProviderService<HotelReservationRequest, HotelReservationResponse> hotelProviderService;

    @Override
    public HotelReservationResponse handle(HotelReservationRequest request) {
        TransactionLogger.getReservationLogger().set(createReservationLog(request));
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        HotelReservationResponse response = hotelProviderService.execute(request);

        stopWatch.stop();
        long elapsedTime = stopWatch.getTotalTimeMillis();

        response.getElapsedTimes().add(new KeyValue(ElapsedTimeType.LCB_ADAPTER.name(), String.valueOf(elapsedTime)));
        TransactionLogger.getReservationLogger().get().setTimeSpan(elapsedTime);

        if (Boolean.valueOf(loadSystemVariable(Constant.APPEND_DERBY_LOG).getValue())) {
            appendLogDetail(request, response);
        }
        return response;
    }

    private ReservationLog createReservationLog(HotelReservationRequest request) {
        ReservationLog reservationLog = new ReservationLog();
        reservationLog.setTaskId(request.getHeader().getTaskId());
        reservationLog.setChannel(request.getHeader().getSource());
        reservationLog.setErsp(request.getHotelReservationRQ().getErsp());
        reservationLog.setHotels(request.getHotelReservationRQ().getHotelReservation().getHotelCode());
        reservationLog.setOperationType(OperationType.HOTEL_RESERVATION);
        return reservationLog;
    }
}
